package com.ft.javaio.nio;

import java.io.FileOutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author RenPu
 * @Date 2023/7/18 10:50
 * @Version 1.0
 * @Description: 模拟磁盘随机/顺序写入数据（利用bytebuffer）
 **/
public class FileChannel_001 {

    public static void main(String[] args) throws Exception {

        //文件输出流
        FileOutputStream outputStream = new FileOutputStream("C:\\Users\\12795\\Desktop\\hello.txt");

        //获取文件输出流Channel对象
        FileChannel channel = outputStream.getChannel();
        //创建buffer对象
        ByteBuffer byteBuffer = ByteBuffer.wrap("my name is niu niu".getBytes());
        //根据通道Channel。写入buffer存储的数据
        channel.write(byteBuffer);

//        //模拟磁盘的顺序写入
//        byteBuffer.rewind();
//        channel.write(byteBuffer);

        //模拟磁盘的随机写入到中间位置
        byteBuffer.rewind();
        channel.position(2);
        channel.write(byteBuffer);


        //释放资源
        channel.close();
        outputStream.close();


    }


}
